<template>
	<l-page :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="100px">
			<el-form-item label="活动编号:" prop="cutSn">
				<el-input v-model.trim="queryParams.cutSn" clearable show-word-limit placeholder="请输入活动编号" />
			</el-form-item>
			<el-form-item label="商品ID:" prop="goodsId">
				<el-input v-model.trim="queryParams.goodsId" maxlength="11" show-word-limit clearable placeholder="请输入商品ID" />
			</el-form-item>
			<el-form-item label="商品名称:" prop="goodsName">
				<el-input v-model.trim="queryParams.goodsName" clearable placeholder="请输入商品名称" />
			</el-form-item>
			<el-form-item label="供应商名称:" prop="supplierName">
				<el-input v-model.trim="queryParams.supplierName" clearable placeholder="请输入供应商名称" />
			</el-form-item>
			<el-form-item label="专区名称:" prop="zoneId">
				<el-select v-model="queryParams.zoneId" clearable filterable placeholder="请选择专区名称">
					<el-option :value="null" label="全部"></el-option>
					<el-option v-for="(value, index) in zoneList" :key="index" :label="value.zoneName" :value="value.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品状态:" prop="isOnSale">
				<el-select v-model="queryParams.isOnSale" clearable filterable placeholder="请选择商品状态">
					<el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</el-form-item>
			<start-end-time ref="child" :get-time="getTime" title="活动时间:"></start-end-time>
		</el-form>

		<div slot="card" class="mb-[24px] flex items-center">
			<l-statistical-card left-name="砍价成功总金额" :left-value="cutStatistics.cutSuccess" :right-value="cutStatistics.todayCutSuccess" />
			<l-statistical-card left-name="砍价失败总金额" :left-value="cutStatistics.cutFail" :right-value="cutStatistics.todayCutFail" />
			<l-statistical-card left-name="砍价中总金额" :left-value="cutStatistics.cutting" :right-value="cutStatistics.todayCutting" />
		</div>
		<template slot="options">
			<l-search @search="queryList" @refresh="resetQuery" />
			<el-button type="primary" icon="el-icon-plus" @click="$router.push('bargainCreate')">新增</el-button>
			<el-button type="primary" @click="goHistory">
				<svg-icon icon-class="grouping" size="16px"></svg-icon>
				砍价记录</el-button
			>
			<el-button type="primary" class="!w-[120px]" @click="handleShowIntegralOpen">
				<svg-icon icon-class="integral" size="16px"></svg-icon>
				商城首页开关</el-button
			>
		</template>
		<el-table v-loading="loading" stripe :data="goodsList">
			<el-table-column :formatter="emptyToString" align="center" label="序号" prop="zoneName" type="index"> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="活动编号" min-width="160" prop="cutSn">
				<template slot-scope="scope">
					{{ scope.row.cutSn ? scope.row.cutSn : '-' }}
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="专区名称" prop="zoneName" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="goodsId" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="goodsName" show-overflow-tooltip min-width="156">
				<template slot-scope="scope">
					<div class="goods-name-style">
						{{ scope.row.goodsName || '-' }}
					</div>
				</template>
			</el-table-column>

			<el-table-column :formatter="emptyToString" align="center" label="商品图片" min-width="120">
				<template slot-scope="scope">
					<el-image :preview-src-list="[scope.row.picUrl]" :src="scope.row.picUrl" style="width: 48px; height: 48px"></el-image>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="供应商名称" prop="supplierName" min-width="120"> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品价格（元）" prop="price" min-width="156"> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="底价（元）" prop="lowPrice" min-width="156"> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="帮砍人数" prop="cutCount" min-width="120" />
			<el-table-column :formatter="emptyToString" align="center" label="砍价时长（h）" prop="cutTime" min-width="156" />
			<el-table-column :formatter="emptyToString" align="center" label="销量" prop="sales" min-width="120"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品状态" prop="isOnSale" min-width="120">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.isOnSale"
						:active-value="1"
						:inactive-value="0"
						active-text="上架"
						class="switch"
						inactive-text="下架"
						@change="statusChange($event, scope.row.cutId)"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="是否参与分佣" prop="isBonus" min-width="120">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.isBonus"
						:active-value="1"
						:inactive-value="0"
						active-text="开启"
						class="switch"
						inactive-text="禁用"
						@change="bonusChange($event, scope.row.cutId)"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="展示顺序" min-width="156" prop="sortOrder">
				<template slot-scope="scope">
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-top" size="mini" type="primary" @click="reSortOrderReduce(scope.row)"></el-button>
					<el-button :circle="true" class="sortOrder" icon="el-icon-caret-bottom" size="mini" type="primary" @click="reSortOrderPlus(scope.row)"></el-button>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="活动时间" min-width="156" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.cutStartTime).format('YYYY-MM-DD HH:mm:ss') }}-</span>
						<span>{{ dayjs(scope.row.cutEndTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :width="100" align="center" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
						<el-button type="danger" @click="handleDel(scope.row.cutId)">删除</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<l-dialog
			v-model="showIntegralOpen"
			title="商城首页显示配置"
			width="477px"
			:show-ok-button="false"
			@formClose="showIntegralOpen = false"
			@close="showIntegralOpen = false"
			@formSubmit="showIntegralOpen = false"
		>
			<el-form :inline="true" label-width="150px">
				<el-form-item label="是否显示在商城首页:">
					<el-switch v-model="dictData.dictValue" active-value="1" inactive-value="0" active-text="开启" class="switch" inactive-text="关闭" @change="handleUpdateStatus(dictData)"></el-switch>
				</el-form-item>
			</el-form>
		</l-dialog>
	</l-page>
</template>
<script>
import { getZoneGoodsList, getZoneList } from '@/api/mall/prefecture';
import { addBargain, delBargain, editBargain, getBargainInfo, getBargainList } from '@/api/mall/bargain';
import startEndTime from '@/components/StartEndTime';
import debounce from 'lodash/debounce';
import tableMixins from '@/mixins/table';

export default {
	name: 'Bargain',
	components: { startEndTime },
	mixins: [tableMixins],
	data() {
		return {
			cutTime: '',
			cutPrice: '',
			cutCount: '',
			editForm: {},
			title1: '',
			showFlag: false,
			price: '',
			date: '',
			zoneId: '',
			selectShowFlag: false,
			loading: true,
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				goodsId: null,
				supplierName: null,
				goodsName: null,
				name: null,
				isOnSale: null,
				cutSn: null,
				categoryId: null,
				date: [],
				zoneId: null,
			},
			statusList: [
				{
					value: null,
					label: '全部',
				},
				{
					value: 0,
					label: '下架',
				},
				{
					value: 1,
					label: '上架',
				},
			],

			goodsList: [],
			// 表单参数
			form: {},
			total: 0,
			showAdd: false,
			// 表单校验
			rules: {
				sort: [
					{ required: true, message: '排序不能为空' },
					{ type: 'number', message: '排序必须为数字值' },
				],
				cutTime: [
					{ required: true, message: '砍价时长不能为空' },
					{ type: 'number', message: '砍价时长必须为数字值' },
				],
				cutCount: [
					{ required: true, message: '砍价人数不能为空' },
					{ type: 'number', message: '砍价人数必须为数字值' },
				],
				cutPrice: [
					{ required: true, message: '砍价金额不能为空' },
					{ type: 'number', message: '砍价金额必须为数字值' },
				],
			},
			goodsDetail: '',
			detailDialogVisible: false,
			zoneList: [],
			goodsForm: {
				pageNum: 1,
				pageSize: 10,
				name: null,
			},
			selectList: [],
			addGoodsFlag: false,
			goodsTotal: 0,
			zoneName: '',
			goodsZoneList: [],
			selectListNow: [],
			disable: true,
			cutId: '',
			cutStatistics: {
				cutFail: 0,
				cutSuccess: 0,
				cutting: 0,
				todayCutFail: 0,
				todayCutSuccess: 0,
				todayCutting: 0,
			},
			dictData: {},
			showIntegralOpen: false,
		};
	},

	created() {
		this.getList();
		this.getZoneList();
		this.getCutStatistics();
	},
	methods: {
		statusChange(event, row) {
			this.$request
				.post('/manage/api/cut/edit', {
					id: row,
					isEnable: event,
				})
				.then(() => {
					this.msgSuccess('编辑成功');
					this.getList();
				});
		},
		bonusChange(event, row) {
			this.$request
				.post('/manage/api/cut/edit', {
					id: row,
					isBonus: event,
				})
				.then(() => {
					this.msgSuccess('编辑成功');
					this.getList();
				});
		},
		handleShowIntegralOpen() {
			this.$request.get('/system/dict/data/list?pageNum=1&pageSize=10&dictType=index_config').then((res) => {
				let data = res.rows;
				for (let i = 0; i < data.length; i++) {
					if (data[i].dictLabel === 'cut_show') {
						this.dictData = data[i];
						this.showIntegralOpen = true;
						return;
					}
				}
			});
		},
		handleUpdateStatus(data) {
			this.$request.put('/system/dict/data', data).then(() => {
				this.$message.success('编辑成功');
			});
		},
		reSortOrderReduce(row) {
			this.$request
				.post('/manage/api/cut/reSortOrderReduce', {
					id: row.cutId,
				})
				.then(() => {
					this.getList();
				});
		},
		reSortOrderPlus(row) {
			this.$request
				.post('/manage/api/cut/reSortOrderPlus', {
					id: row.cutId,
				})
				.then(() => {
					this.getList();
				});
		},
		getCutStatistics() {
			this.$request.get('/manage/api/cut/cutStatistics').then((res) => {
				this.cutStatistics = res.data;
			});
		},
		goHistory() {
			this.$router.push({
				path: '/marketing/cutHistory',
			});
		},
		handleClose3() {
			this.showFlag = false;
			this.editForm = {};
			this.$refs['editForm'].resetFields();
		},
		batchEditCount() {
			console.log(this.date);
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'cutCount', this.cutCount);
			}
		},
		batchEditTime() {
			console.log(this.date);
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'cutTime', this.cutTime);
			}
		},
		batchEditPrice() {
			for (let i = 0; i < this.selectListNow.length; i++) {
				this.$set(this.selectListNow[i], 'cutPrice', this.cutPrice);
			}
		},
		goodsCommit: debounce(
			function () {
				if (!this.selectListNow.length) {
					this.$message.error('请选择商品!!!');
					return;
				}
				for (let i = 0; i < this.selectListNow.length; i++) {
					if (!this.selectListNow[i].cutPrice) {
						this.$message.error('请输入商品的砍价金额');
						return;
					}
					if (this.selectListNow[i].cutPrice > this.selectListNow[i].price) {
						this.$message.error('砍价金额不能大于商品金额');
						return;
					}
					if (!this.selectListNow[i].cutCount) {
						this.$message.error('请输入商品的砍价人数');
						return;
					}
					if (!this.selectListNow[i].cutTime) {
						this.$message.error('请输入商品的砍价时间');
						return;
					}
					if (!this.selectListNow[i].sort) {
						this.$message.error('请添加商品的排序');
						return;
					}

					delete this.selectListNow[i].tenantId;
					this.selectListNow[i].zoneId = this.zoneId;
				}
				addBargain(this.selectListNow).then((res) => {
					this.$message.success('新增砍价商品成功!');
					this.showAdd = false;
					this.handleClose();
					this.getList();
				});
			},
			1500,
			{
				leading: true,
				trailing: false,
			}
		),
		queryGoodsList() {
			this.goodsForm.pageNum = 1;
			this.getGoodsList();
		},
		getGoodsList() {
			this.goodsForm.zoneId = this.zoneId;
			getZoneGoodsList(this.goodsForm).then((response) => {
				this.goodsZoneList = response.data.records;
				this.goodsTotal = response.data.total;
				this.addGoodsFlag = true;
			});
		},
		submit() {
			this.selectListNow = this.selectList;
			this.addGoodsFlag = false;
		},
		selectGoodsChange(value) {
			this.selectList = value;
		},
		handleClose2() {
			this.goodsForm = {
				pageNum: 1,
				pageSize: 10,
				name: null,
			};
			this.selectList = [];
			this.addGoodsFlag = false;
		},
		getZoneList() {
			getZoneList({}).then((res) => {
				this.zoneList = res.data;
			});
		},
		selectShow() {
			this.addGoodsFlag = true;
			this.getGoodsList();
		},
		handleClose() {
			this.showAdd = false;
			this.price = '';
			this.selectListNow = [];
			if (this.$refs.selectTable) {
				this.$refs.selectTable.clearSelection();
			}
			this.selectList = [];
			this.zoneId = '';
		},
		resetQuery() {
			this.$refs.child.resetTime(); // 清空时间
			this.resetForm('queryForm');
			this.queryList();
		},
		//获取时间
		getTime(startTime, endTime) {
			this.queryParams.startTime = startTime;
			this.queryParams.endTime = endTime;
		},
		queryList() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		getList() {
			this.loading = true;
			getBargainList(this.queryParams)
				.then((response) => {
					this.goodsList = response.data.records;
					this.total = response.data.total;
					this.setActionWidth();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {};
			this.resetForm('form');
		},
		getKillGoodsDetails(id) {
			getBargainInfo({ id }).then((res) => {
				this.editForm = res.data;
				console.log(this.editForm);
			});
		},
		handleUpdate(id) {
			this.getKillGoodsDetails(id);
			this.showFlag = true;
			this.disable = true;
			this.title1 = '详情';
		},
		submitEdit() {
			this.$refs['editForm'].validate((valid) => {
				if (valid) {
					let obj = {
						id: this.cutId,
						cutPrice: this.editForm.cutPrice,
						cutCount: this.editForm.cutCount,
						cutTime: this.editForm.cutTime,
						sort: this.editForm.sort,
					};
					editBargain(obj).then((res) => {
						this.$message.success('编辑商品成功!');
						this.getList();
						this.handleClose3();
					});
				}
			});
		},
		handleEdit(id) {
			this.cutId = id;
			this.getKillGoodsDetails(id);
			this.showFlag = true;
			this.disable = false;
			this.title1 = '编辑';
		},
		handleDel(id) {
			this.$confirm('是否删除该商品?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delBargain({
					id: [id],
				}).then(() => {
					this.$message.success('删除商品成功!');
					this.getList();
				});
			});
		},
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
				}
			});
		},
		handleAdd() {
			this.showAdd = true;
		},
		handleCommand(key, row) {
			this[key](row);
		},
	},
};
</script>
<style lang="scss" scoped>
.sortOrder {
	background: #ffffff;
	border-color: #cccccc;
	color: #86909c;
}

.sortOrder .el-icon-caret-top {
	color: #cccccc;
}

.sortOrder .el-icon-caret-bottom {
	color: #cccccc;
}
</style>
